import { RequestMethod } from "../lib/defines";
import { RoomBase } from "../utils/types";

export default function dissolveClassroom (app) {
  const { socket, rooms } = app.locals;
  const { userId, username } = socket.handshake.query;
  const { dissolve } = RequestMethod;

  /**
   * 销毁房间
   */
  socket.on(dissolve, function dissolve (room: RoomBase, cb) {
    const __room = rooms[room.classId]
    const member = { userId, username }

    if (__room) {
      room = Object.assign(room, __room.json())

      /**
       * 2秒 等待接听时间
       */
      socket
        .timeout(1000 * 2)
        .to(room.classId)
        .emit('dissolve', { room, member }, () => {

          __room.getMembers().forEach(member => {
            member.stop(userId)
          })

          // 删除对应房间
          rooms[room.classId] = null;

          // 回调
          if (cb) {
            cb({ status: 'ok', resolve: 'dissolved' })
          }
        });
    } else {
      // 删除对应房间
      rooms[room.classId] = null;
      console.error('room not find!')
    }
  });
}
